#include "opsimplex.h"
#include "miscutils.h"
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>

/*
 * trataParams: le e valida parâmetros de entrada do programa
 */
void trataParams(int argc, char** argv, FILE* f){
	if (argc < 2) showUsage();
	if (!strcmp(argv[1],"help")) showUsage();
	if (f == NULL) dieHelp(MSG_ERR_ARQ);
	int i;
	unsigned int d = 7;
	verbose = 0;
	stats = 0;
	ttotal = 0.0;
	t1 = 0.0;
	t2 = 0.0;
	for (i=2;i<argc;i++){
		if (!strcmp(argv[i],"-v")) verbose = 1;
		else if (!strcmp(argv[i],"-s")) stats = 1;
		else if (!strcmp(argv[i],"-p")) {
			if (i+1>=argc||!sscanf(argv[++i],"%u",&d)) die(MSG_ERR_PREC);
			char* bu;
			sprintf(bu,"%u",d);
			if (strcmp(bu,argv[i])) dieHelp(MSG_ERR_PREC);
		}
		else warning(MSG_PARAM_N);
	}

	mu_delta = 1.0;
	for(i=0;i<d;i++) mu_delta/=10.0;
}

int main(int argc, char** argv){
	FILE* entrada = fopen(argv[1],"r");
	trataParams(argc,argv,entrada);

	if (verbose) fprintf(stderr,"file opened propperly\n");

	time_t tini, tfim;
	int m,n,rc;

	fscanf(entrada,"%d %d",&m,&n);
	if (m<=0||n<=0||n<m) dieHelp(MSG_ERR_MF);
	if (verbose) fprintf(stderr,"size read from file: m=%d n=%d\n",m,n);

	PMatriz A, c, b, x, sol;
	A = inicia(m,n);
	c = inicia(1,n);
	b = inicia(m,1);
	x = inicia(n,1);
	sol = inicia(1,1);

	leVetor(entrada,c,n,0);
	if (verbose) fprintf(stderr,"cost vector read from file\n");
	leVetor(entrada,b,m,1);
	if (verbose) fprintf(stderr,"resources vector read from file\n");
	leMatriz(entrada,A,m,n);
	if (verbose) fprintf(stderr,"restriction matrix read from file\n");

	tini = time(NULL);

	rc = simplexDuasFazes(A,c,b,x);

	tfim = time(NULL);
	ttotal = difftime(tini,tfim);

	if (rc == SIMPLEX_RET_OT){
		if (!mult(c,x,sol)) die(MSG_ERR_UK);
		fprintf(stdout,"optimal solution found\nx values:\n");
		impVetor(stdout,x);
		fprintf(stdout,"solution value: %lf\n",getEscalar(sol));
	}
	if (rc == SIMPLEX_RET_IL)
		fprintf(stdout,"problem unbounded\n");
	if (rc == SIMPLEX_RET_INV)
		fprintf(stdout,"problem infeasible\n");

	if (stats){
		fprintf(stdout,"total execution time: %lf\nexecution time for first phase: %lf\nexecution time for second phase: %lf\n",ttotal,t1,t2);
		fprintf(stdout,"number of iteration in first phase: %d\n",it1);
		fprintf(stdout,"number of iteration in second phase: %d\n",it2);
	}


	fclose(entrada);
	return 0;
}
